package com.lengyu.vxminiprogram.common;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class CommonUtils {
    /**
     * 判断时间戳是否是当天
     * @param timestamp
     * @return
     */
    public static boolean isToday(long timestamp) {
        Calendar c = Calendar.getInstance();
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND);
        long firstOfDay = c.getTimeInMillis(); // 今天

        c.setTimeInMillis(timestamp);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间

        return firstOfDay == c.getTimeInMillis();
    }

    /**
     * 判断时间戳是否是当天
     * @param timestamp
     * @return
     */
    public static long getDayZeroTime(long timestamp) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间

        return c.getTimeInMillis();
    }

    /**
     * 判断时间戳是否是当天
     * @param timestamp
     * @return
     */
    public static long getMonthZeroTime(long timestamp) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        c.set(Calendar.DAY_OF_MONTH,1);
        return c.getTimeInMillis();
    }
    /**
     * 判断时间戳是否是当天
     * @param timestamp
     * @return
     */
    public static long getNextMonthZeroTime(long timestamp) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        c.set(Calendar.DAY_OF_MONTH,1);
        if (c.get(Calendar.MONTH) == 12) {
            c.set(Calendar.MONTH,1);
            c.set(Calendar.YEAR,c.get(Calendar.YEAR) + 1);
        }
        else{
            c.set(Calendar.MONTH,c.get(Calendar.MONTH) + 1);
        }
        return c.getTimeInMillis();
    }

    /**
     * 判断时间戳是否是当天
     * @param timestamp
     * @return
     */
    public static long getYearZeroTime(long timestamp) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        c.set(Calendar.DAY_OF_MONTH,1);
        c.set(Calendar.MONTH,1);
        return c.getTimeInMillis();
    }

    /**
     * 判断时间戳是否是当天
     * @param timestamp
     * @return
     */
    public static String getYearString(long timestamp) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        c.set(Calendar.DAY_OF_MONTH,1);
        c.set(Calendar.MONTH,1);
        return String.valueOf(c.get(Calendar.YEAR));
    }
    /**
     * 判断时间戳是否是当天
     * @param timestamp
     * @return
     */
    public static long getNextYearZeroTime(long timestamp) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        c.set(Calendar.DAY_OF_MONTH,1);
        c.set(Calendar.MONTH,1);
        c.set(Calendar.YEAR,c.get(Calendar.YEAR) + 1);
        return c.getTimeInMillis();
    }
//    public static String timeToStrYMD(long timestamp){
//        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
//        return  sdf.format(timestamp);
//    }

    public static String timeToStrYMDHMS(long timestamp){
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(timestamp);
//        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return  sdf.format(c.getTimeInMillis());
    }

    public static String todayYMD(){
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return  sdf.format(c.getTimeInMillis());
    }

    public static Date getTodayZeroDate(){
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        return  c.getTime();
    }

    public static Date getDateBeforeTodayZeroDate(int dayCount){
        Calendar c = Calendar.getInstance();
        long beforeTime = System.currentTimeMillis() - (1000*60*60*24*dayCount);
        c.setTimeInMillis(beforeTime);
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        return  c.getTime();
    }

    public static String YMDToStr(Date date){
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(date.getTime());
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return  sdf.format(c.getTimeInMillis());
    }

    public static Date YMDToDate(String dateStr){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
        return  date;
    }

    public static Date StrToDate(String dateStr,String formatter){
        SimpleDateFormat sdf=new SimpleDateFormat(formatter);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
        return  date;
    }

    public static String yesterdayYMD(){
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis() - 1000 * 60 * 60 * 24 );
        clearCalendar(c, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND); // 指定时间戳当天最早时间
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        return  sdf.format(c.getTimeInMillis());
    }

    private static void clearCalendar(Calendar c, int... fields) {
        for (int f : fields) {
            c.set(f, 0);
        }
    }

    public static String enCodeSHA2(String dataStr){
        try {
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            String salt = "some_random_salt";
            String passWithSalt = dataStr + salt;
            byte[] passBytes = passWithSalt.getBytes();
            byte[] passHash = sha256.digest(passBytes);
            StringBuilder sb = new StringBuilder();
            for(int i=0; i< passHash.length ;i++) {
                sb.append(Integer.toString((passHash[i] & 0xff) + 0x100, 16).substring(1));
            }

            String generatedPassword = sb.toString();

            return generatedPassword;

        } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }

        return null;

    }
    public static QueryWrapper getQueryWrapper(BasePageParamDto pageParamDto,JSONObject specialParamConfig){
        QueryWrapper queryWrapper = new QueryWrapper();
        JSONObject paramJson = pageParamDto.getParamMapObj();
        if(paramJson != null){
            for(String key:paramJson.keySet()){
                if(key.endsWith("_queryStartDate") || key.endsWith("_queryEndDate")){
                    if(paramJson.get(key) == null){
                        continue;
                    }
                    else{
                        if(key.endsWith("_queryStartDate")){
                            queryWrapper.ge(key.replace("_queryStartDate",""),new Date(paramJson.getLong(key)));
                        }
                        else if (key.endsWith("_queryEndDate")){
                            queryWrapper.lt(key.replace("_queryEndDate",""),new Date(paramJson.getLong(key)));
                        }
                    }
                }
                else{
                    if(paramJson.get(key) == null){
                        continue;
                    }
                    else if(paramJson.get(key) instanceof String){
                        if(StringUtils.isNotBlank(paramJson.getString(key))){
                            queryWrapper.like(key,paramJson.getString(key));
                        }
                    }
                    else if(paramJson.get(key) instanceof ArrayList){
                        if(specialParamConfig.containsKey(key)){
                            if(specialParamConfig.getString(key).equals("range")){
                                queryWrapper.ge(key,((List)(paramJson.get(key))).get(0));
                                queryWrapper.lt(key,((List)(paramJson.get(key))).get(1));
                            }
                        }
                    }
                    else {
                        queryWrapper.eq(key,paramJson.get(key));
                    }
                }

            }
        }
        return queryWrapper;
    }

    public static QueryWrapper getQueryWrapper(BasePageParamDto pageParamDto){
       return getQueryWrapper(pageParamDto,new JSONObject());
    }

    public static long getHourCountToNow(long calcTime) {
       long milliSeconds = System.currentTimeMillis() - calcTime;
       if(milliSeconds > 0){
           if(milliSeconds % (1000 * 60 * 60 * 24) == 0){
               return milliSeconds / (1000 * 60 * 60 * 24);
           }
           else{
               return (milliSeconds / (1000 * 60 * 60 * 24)) + 1;
           }
       }
       return 0;
    };
//    /** * mongo 日期查询isodate * @param dateStr * @return */
//    public static Date dateToISODate(Date date){
//        //T代表后面跟着时间，Z代表UTC统一时间
//        SimpleDateFormat format =
//                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
//        format.setCalendar(new GregorianCalendar(new SimpleTimeZone(0, "GMT")));
//        String isoDate = format.format(date);
//        try {
//            return format.parse(isoDate);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

}
